#include "DLLWrapper.h"
#include <QApplication>
#include <json/writer.h>

DLLWrapper::DLLWrapper()
{	
}

DLLWrapper::~DLLWrapper()
{	
	Json::Value param;	
	DealCommand("exit",param);
}

bool DLLWrapper::init(QString name)
{
	QString path = QApplication::instance()->applicationDirPath() + "/plugins/CVR100UD";
	QString exe = QApplication::instance()->applicationFilePath();
	QStringList params;
	params << name;

	m_process.setWorkingDirectory(path);	
	m_process.start(exe,params);
	if(!m_process.waitForStarted())
		return false;

	Json::Value param;
	param["dll"] = qPrintable(name);
	Json::Value ret = DLLWrapper::DealCommand("init",param);
	return ret["code"].asInt() == 0;
}

Json::Value DLLWrapper::DealCommand(QString cmd,Json::Value &param)
{
	Json::Value json_ret;	
	if(m_process.state() != QProcess::Running)
	{
		json_ret["code"] = -1;
		json_ret["message"] = "DLL state error";
		return json_ret;
	}
	
	Json::FastWriter w;
	Json::Reader r;
	param["InternalCommand"] = qPrintable(cmd);
	string str = w.write(param);

	QByteArray data(str.data(),str.size());
	data = data.toBase64();
	m_process.write(data.data());
	if(!m_process.waitForReadyRead(1000))
	{
		json_ret["code"] = -1;
		json_ret["message"] = "Call DLL Error";
		return json_ret;
	}

	QByteArray recv = m_process.readAllStandardOutput();
	recv = QByteArray::fromBase64(recv);

	if(r.parse(recv.data(),json_ret))
		return json_ret;
	else
	{
		json_ret.clear();
		json_ret["code"] = -1;
		json_ret["message"] = "DLL recv invaild";
		return json_ret;
	}
}